<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/1/3
 * Time: 13:52
 */
class Sina extends MY_View_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->config->load('sina');


    }

    function index(){
        $data = $this->config->item('sina');
        $this->load->library('Sina_auth',$data);
        $callback_url = urlencode(site_url('auth/sina'));
        if(isset($_GET['code']) && $_GET['code']!='') {
            $result = $this->sina_auth->access_token($callback_url, $_GET['code']);
            if (isset($result['access_token']) && $result['access_token'] != '') {
                $_SESSION['sina'] = $result['access_token']; //access token
                redirect(site_url('auth/sina/login'));
            } else {
                show_error('授权失败', 401);
            }
        }else{
            $callback_url = urlencode(site_url('auth/sina'));
            $login_url = $this->sina_auth->login_url($callback_url);
            header("Location: " . $login_url, TRUE, 301);
            exit;
        }
    }

    function login(){

        $sina =isset($_SESSION['sina'])?$_SESSION['sina']:'';
        //检查是否已登录
        if($sina!=''){
            //获取登录用户id
            $data = $this->config->item('sina');
            $this->load->library('Sina_auth',$data);
            $data['access_token'] = $sina;
            $sina_uid= $this->sina_auth->get_uid();
            $uid=$sina_uid['uid'];
            //获取登录用户信息
            $result= $this->sina_auth->show_user_by_id($uid);
            if(isset($result['error_code'])){
                show_error('授权失败', 401);
            }else{
                $user_info = (array) json_decode($result);
                $this->load->model('auth/Users');
                $this->load->model('auth/User_sina');
                $user_id = $this->User_sina->get_user_by_sina($user_info['id']);
                if (!$user_id) {
                    $username = preg_replace("/[^a-zA-Z0-9\x80-\xff_]+/", "", $user_info['nickname']);
                    if (strlen($username) == 0) {
                        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        $username = substr(str_shuffle(str_repeat($pool, 5)), 0, 6);
                    }
                    $username = $username.random_string('numeric', 4);

                    //无用户，创建用户
                    switch($user_info['gender']){
                        case 'm':
                            $gender = 1;
                            break;
                        case 'wm':
                            $gender = 0;
                            break;
                        default:
                            $gender = -1;
                    }

                    $extend = array(
                        'avatar'                =>  $user_info['avatar_large'],
                        'nickname'				=>	$user_info['nickname'],
                        'gender'				=>	$gender,
                        'address'				=>	$user_info['location'],
                        'introduce'             =>  $user_info['description'],
                        'from'					=>	'sina',
                    );
                    $user = $this->auth_nuan->create_user_third($username, '111111', $extend);
                    $sina_info = array(
                        'user_id'               =>  $user['user_id'],
                        'sina_id'		        =>  $user_info['id'],
                        'sina_url'	            =>	$user_info['url'],
                        'sina_auth_time'		=>	date("Y-m-d H:i:s"),
                        'sina_auth_num'		=>	0
                    );
                    $this->User_sina->insert($sina_info);
                    $error = $this->auth_nuan->get_error_message();
                    if ($error) {
                        foreach ($error as $key => $msg) {
                            show_error($msg);
                        }
                    }
                    $user['id'] = $user['user_id'];
                }
                $user = $this->Users->get_user_by_id($user_id['user_id']);
                if (is_object($user)) {
                    $user = (array) $user;
                }
                $this->auth_nuan->set_logged_session($user);
                $this->auth_nuan->create_autologin($user['id']);
            }
        }else{
            $callback_url = urlencode(site_url('auth/sina'));
            $login_url = $this->sina_auth->login_url($callback_url);
            header("Location: " . $login_url, TRUE, 301);
            exit;
        }
    }
}